//线程的封装
#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include<functional>
using namespace std;

namespace ThreadModule{

    typedef void (*func_t)(const std::string &name); // 函数指针类型:返回值是void 
    class Thread
    {
        public:
        void Excute()
        {
            std::cout << _name << " is running" << std::endl;
            _isrunning = true;
            _func(_name);
            _isrunning = false;
        }
        public:
        Thread(const std::string &name, func_t func):_name(name), _func(func)
        {
            std::cout << "create " << name << " done" << std::endl;
        }
            static void* ThreadRoutine(void* args)//这是类里面的，默认有this，和创建的主线程参数不匹配所以要加static;新线程都会执行该方法，
            {
                Thread* self = static_cast<Thread*>(args);//获得了当前对象
                self->Excute();//调用回调函数
                return nullptr;
            }
            bool Start()
            {
                int n = ::pthread_create(&_tid,nullptr,ThreadRoutine,nullptr);//使用的是pthread库里面的
                if(n!=0)
                {
                    return false;
                }
                return true;
            }
            std::string Status()//线程启动了检测状态
            {
                if(_isrunning) return "running";
                else return "sleep";
            }
            std::string Name()
            {
                return _name;
            }
            void Stop()
            {
                if(!_isrunning)
                {
                    pthread_cancel(_tid);
                    _isrunning=false;
                }
            }
            void Join()
            {
                pthread_join(_tid,nullptr);
            }
            ~Thread()
            { }
        private:
            string _name;
            pthread_t _tid;
            bool _isrunning;
            func_t _func;//线程要执行的回调函数

    };
}